package org.hepeng.workx.spring.security.authentication.event;

import lombok.extern.slf4j.Slf4j;
import org.hepeng.workx.web.util.HttpRequestUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;

import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @author he peng
 */

@Slf4j
public class AuthenticationSuccessLoggerListener implements ApplicationListener<AuthenticationSuccessEvent> {

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {

        Authentication auth = event.getAuthentication();
        HttpSession session = HttpRequestUtils.getHttpServletRequest().getSession(false);
        String sessionId = "";
        if (Objects.nonNull(session)) {
            sessionId = session.getId();
        }
        log.info("\n\n" +
                "********************************************************************\n" +
                "{} Authentication Success \n" +
                "HTTP Session Id {} \n" +
                "********************************************************************\n\n"
                , auth.getName() , sessionId);
    }
}
